<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目" prop="projectId">
        <el-select clearable="" v-model="queryParams.projectId" filterable placeholder="请选择项目">
          <el-option v-for="item in projectList" :key="item.id" :label="item.projectName" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="算法库ID" prop="displaySkuSoId">
        <el-select clearable="" v-model="queryParams.displaySkuSoId" filterable placeholder="请选择算法">
          <el-option v-for="item in displayAlgoV5_list" :key="item.soId" :label="item.soId+'-'+item.name" :value="item.soId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品ID" prop="skuId">
        <el-input
          v-model="queryParams.skuId"
          placeholder="请输入商品ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="skuName">
        <el-input
          v-model="queryParams.skuName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['genius:platform-project-display-goods:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleBatch">批量新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['genius:platform-project-display-goods:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['genius:platform-project-display-goods:removed']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['genius:platform-project-display-goods:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="PlatformProjectDisplayGoodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="项目ID" align="center" prop="projectId" />
      <el-table-column label="商品ID" align="center" prop="skuId" />
      <el-table-column label="商品名称" align="center" prop="skuName" />

      <el-table-column prop="imageUrl" label="SKU图片" align="center">
            <template slot-scope="scope">
              <div>
                <el-popover
                  trigger="hover"
                  placement="bottom"
                  width="400"
                  v-if="scope.row.imageUrl"
                >
                  <img
                    slot="reference"
                    :src="scope.row.imageUrl"
                    height="50"
                    v-if="scope.row.imageUrl"
                  />
                  <img
                    :src="scope.row.imageUrl"
                    style="width: 300px"
                    v-if="scope.row.imageUrl"
                  />
                </el-popover>
                <span v-if="!scope.row.imageUrl">-</span>
              </div>

              <!-- <img :src="scope.row.imageUrl" alt="" height="50" /> -->
            </template>
          </el-table-column>
          <el-table-column prop="properties" label="属性" align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.properties == 1">纯净水</div>
              <div v-if="scope.row.properties == 2">果汁</div>
              <div v-if="scope.row.properties == 3">奶制品</div>
              <div v-if="scope.row.properties == 4">气泡水</div>
            </template>
          </el-table-column>
          <el-table-column prop="capacity" label="规格" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.capacity }}{{ scope.row.unit }}</span>
            </template>
          </el-table-column>


      <el-table-column label="算法库ID" align="center" prop="displaySkuSoId" />
      <el-table-column label="品类" align="center" prop="goodsType">
        <template slot-scope="scope">
          <el-tag v-show="scope.row.goodsType === 0 " type="success">本品</el-tag>
          <el-tag v-show="scope.row.goodsType === 1 " type="info">竞品</el-tag>
          <el-tag v-show="scope.row.goodsType === 2 " type="warning">他品</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="必铺品" align="center" prop="mustGoods">
        <template slot-scope="scope">
          <el-tag v-show="scope.row.mustGoods === 0 " effect="plain" type="warning">是</el-tag>
          <el-tag v-show="scope.row.mustGoods === 1 " effect="plain" type="info">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="新品" align="center" prop="newGoods">
        <template slot-scope="scope">
          <el-tag v-show="scope.row.newGoods === 0 " effect="dark" type="danger">是</el-tag>
          <el-tag v-show="scope.row.newGoods === 1 " effect="dark" type="info">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['genius:platform-project-display-goods:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['genius:platform-project-display-goods:removed']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改平台陈列V5柜商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="96px">
        <el-form-item label="项目" prop="projectId" required>
          <el-select clearable="" v-model="form.projectId" filterable placeholder="请选择项目">
            <el-option v-for="item in projectList" :key="item.id" :label="item.projectName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="算法库ID" prop="displaySkuSoId" required>
          <el-select clearable="" v-model="form.displaySkuSoId" filterable placeholder="请选择算法">
            <el-option v-for="item in displayAlgoV5_list" :key="item.soId" :label="item.soId+'-'+item.name" :value="item.soId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品ID" prop="skuId" required>
          <el-input v-model="form.skuId" placeholder="商品唯一标识，不可修改" style="width:217px"/>
        </el-form-item>
        <el-form-item label="商品名称" prop="skuName" required>
          <el-input v-model="form.skuName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="属性" prop="properties">
              <el-select
                v-model="form.properties"
                placeholder="商品属性"
                clearable
                style="width: 240px"
              >
                <el-option
                  v-for="dict in dict.type.goods_properties"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-row>
              <el-col :span="12">
                <el-form-item label="容量" prop="capacity" >
                  <el-input
                    type="number"
                    v-model="form.capacity"
                    placeholder="请输入商品容量"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="容量单位" prop="unit" >
                  <el-input v-model="form.unit" placeholder="ml/g/L" />
                  <!-- <el-select
                    v-model="form.unit"
                    placeholder="请选择容量单位"
                    clearable
                  >
                    <el-option
                      v-for="item in uniteList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select> -->
                </el-form-item>
              </el-col>
            </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="品类" prop="goodsType" required="">
              <el-select v-model="form.goodsType" placeholder="请选择商品品类" clearable>
                <el-option v-for="dict in dict.type.goods_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否为必铺品" prop="mustGoods" >
              <el-radio-group v-model="form.mustGoods" :disabled="parseInt(this.form.goodsType) !== 0">
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否为新品" prop="newGoods" required>
              <el-radio v-model="form.newGoods" label="0">是</el-radio>
              <el-radio v-model="form.newGoods" label="1">否</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
              <el-col :span="24">
                <el-form-item label="SKU图片" prop="file">
                  <el-upload
                    class="avatar-uploader"
                    :action="
                      uploadFileUrl + '?fileTypeCode=' + this.fileTypeCode
                    "
                    :show-file-list="false"
                    :data="uploadData"
                    :headers="headers"
                    :on-success="handleUploadSuccess"
                  >
                    <img
                      v-if="imageUrl || form.imageUrl"
                      :src="imageUrl || form.imageUrl"
                      class="avatar"
                    />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量导入商品SKU -->
    <el-dialog :title="batchTitle" :visible.sync="batchOpen" width="700px" append-to-body>
      <div style="text-align: center;">
        模板：<ExportExcel :list="exportList" :tHeader="oHeader" :tValue="oValue" filename="商品SKU批量导入Excel模板">模板下载</ExportExcel>
      </div>
      <div style="text-align: center;margin-top: 5%;">
        <el-upload
        class="upload-demo"
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          action = "/"
          :on-change="handUploadExcel"
          :show-file-list="true"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :auto-upload="false"
          drag  
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitFileForm">开始导入</el-button>

      </div>
      </el-dialog>
  </div>
</template>

<script>
import { listPlatformProjectDisplayGoods, getPlatformProjectDisplayGoods, removedPlatformProjectDisplayGoods, addPlatformProjectDisplayGoods, updatePlatformProjectDisplayGoods, batchInsertPlatformProjectDisplayGoods } from "@/api/genius/platform-project-display-goods";
import { getProjectList } from '@/api/projectSku/projectSku';
import { listDisplayAlgoV5 } from "@/api/genius/platform-display-algo-v5";
import ExportExcel from '@/components/ExcelUtils/Export2Excel.vue';
import { getToken } from '@/utils/auth';
import * as XLSX from 'xlsx';
export default {
  name: "Platform-project-display-goods",
  dicts:['goods_type',"goods_properties"],
  components: { ExportExcel },
  data() {
    return {
      //批量新增弹窗
      batchOpen:false,
      //批量新增标题
      batchTitle:"",
      //上传的文件
      excelFileData:'',
      // 导出数据集合
      exportList: [{"projectId":"1","displaySkuSoId":"625","skuId":'6920459996508',"skuName":"示例：绿茶_康师傅_1000ml","goodsType":"	填数字(0：本品，1：竞品，2：它品)","mustGoods":"填数字，注意：必铺品的品类一定是本品(0：必铺，1：非必铺)","newGoods":"填数字,新品的品类一定是本品(0：新品，1：非新品)","remark":""}],
      // 导出样例的抬头和数据
      oHeader: ['项目id','算法库id','商品id','商品名称','品类','是否为必铺品','是否为新品','备注'],
      oValue:['projectId','displaySkuSoId','skuId','skuName','goodsType','mustGoods','newGoods','remark'], 
      //批量导入上传
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      // 算法列表
      displayAlgoV5_list:[],
      // 项目列表
      projectList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 平台陈列V5柜商品表格数据
      PlatformProjectDisplayGoodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        displaySkuSoId: null,
        skuId: null,
        skuName: null,
        projectId: null,
        removed: null,
        orderByColumn:'id',
        isAsc:'desc'
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      //sku图片上传
      uploadData: {
        userId: this.$store.state.user.id,
      },
      uploadFileUrl:
        process.env.VUE_APP_BASE_API + "/file/oss-controller/upload-file", // 上传文件服务器地址
      fileTypeCode: 3,
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      imageUrl:"",
    };
  },
  created() {
    this.getList();
    this.getProject();
    this.getDisplayAlgoV5List(); // 获取算法列表
  },
  watch: {
    'form.goodsType': function (val, old) {
      if (val === '' ) {
        this.form.mustGoods = null;
      }else if(val === '1' || val === '2'){
        this.form.mustGoods = 1;
      }
    },
  },
  methods: {
     // 文件上传中处理
     handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    handUploadExcel(file,fileList){
      // 校验文件
      if (!file) {
        this.$confirm("读取excel文件数据失败，请尝试重新上传文件！", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
        // 如果没有文件 - 当然也可以提醒用户弹个警告框 但是基本没有这种情况的出现
        return false;
      }else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
        // 文件格式的判断
        this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      // 准备读取文件数据
      this.excelFileData = file
      this.$message.success("上传成功")
    },
    // // 文件上传成功处理
    // handleFileSuccess(response, file, fileList) {
    //   this.upload.open = false;
    //   this.upload.isUploading = false;
    //   this.$refs.upload.clearFiles();
    //   this.$alert(
    //     "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
    //       response.msg +
    //       "</div>",
    //     "导入结果",
    //     { dangerouslyUseHTMLString: true }
    //   );
    //   // this.getList();
    // },
    // 提交上传文件
    submitFileForm() {
      if(this.excelFileData){
        const fileReader = new FileReader(this.excelFileData);
        fileReader.onload = (ev) => {
          try {
            const data = ev.target.result;
            let workbook = XLSX.read(data, {
              type: "binary",
            });
            // 取第一张表
            const wsname = workbook.SheetNames[0];
            // 生成json表格内容
            let ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);
            // 循环 ws 取得其中的数据 
            // 把 ws 打印出来 就可以看得很清楚了 之后就进行自己想要的操作就可以了
            // 没有一样的代码 没有一样的需求
            if(ws.length>0){
                var temporary = [];
                for (let i = 0; i < ws.length; i++) {
                    let temp = {
                      projectId:ws[i].项目id,
                      displaySkuSoId:ws[i].算法库id,
                      name:ws[i].算法名称,
                      skuId:ws[i].商品id,
                      skuName:ws[i].商品名称,
                      goodsType:ws[i].品类,
                      mustGoods:ws[i].是否为必铺品,
                      newGoods:ws[i].是否为新品,
                      remark:ws[i].备注
                    }
                    temporary.push(temp)
                }
                // 判断是否有重复的soId
                for(let i = 0; i < temporary.length; i++){
                  if((temporary[i].newGoods == 0 || temporary[i].mustGoods == 0) && temporary[i].goodsType != 0){
                    this.$message.warning("必铺品和新品的品类必须是本品，请检查skuId为:"+temporary[i].skuId+"的配置");
                    return;
                  }
                  for(let j = i+1; j < temporary.length; j++){
                    if(temporary[i].skuId == temporary[j].skuId){
                      this.$message.warning("skuId不能重复，请检查excel:"+temporary[i].skuId)
                      return;
                    }
                  }
                }
                if(temporary.length === 0){
                  this.$message.warning("未读取合法数据，请检查excel")
                  return
                }
                this.$notify({
                  title: '提示',
                  message: '批量注册中,请稍后…',
                  offset: 700,
                  duration: 0
                });
                batchInsertPlatformProjectDisplayGoods(temporary)
                .then((res) => {
                  if(res.code === 200){
                    this.$message.success("批量新增成功,详情："+res.msg)
                    this.batchOpen = false
                    this.getList()
                  }else{
                    this.$message.warning("批量新增失败，原因："+res.msg)
                  }
                  this.$notify.closeAll();//去掉交互框
                  this.reset()
                })
                .catch((err) => {
                  this.$message.error('错误：'+err.message);
                }).finally(()=>{
                  this.$notify.closeAll();//去掉交互框
                  this.batchOpen = false
                  this.getList();
                  this.reset()
                  this.$refs.upload.clearFiles()
                })
             
            }else{
                this.$message({
                  type: "info",
                  message: "获取的列表为空，请检查表格是否有数据!",
                });
            }

          } catch (e) {
            return false;
          }
        };
        // 如果为原生 input 则应是 files[0]
        fileReader.readAsBinaryString(this.excelFileData.raw);
      }else{
        this.$message({
          type: 'warning',
          message: '请先上传Excel'
        })
      }
    },
    handleBatch(){
      this.reset();
      this.batchOpen = true;
      this.batchTitle = "批量新增算法SKU";
    },
    /** 获取风幕算法列表 */
    getDisplayAlgoV5List(){
      // 查询参数
      let params =  {
        pageNum: 1,
        pageSize: 10000,
      }
      listDisplayAlgoV5(params).then(response => {
        if(response.code === 200){
          this.displayAlgoV5_list = response.data.data;
        }else{
          this.$message.error("v5算法获取失败,原因："+response.msg)
        }
      })
    },
    /**获取项目列表 */
    getProject() {
      getProjectList().then((res) => {
        if (res.code === 200) {
          this.projectList = res.rows
        }
      })
    },
    /** 查询平台陈列V5柜商品列表 */
    getList() {
      this.loading = true;
      listPlatformProjectDisplayGoods(this.queryParams).then(response => {
        this.PlatformProjectDisplayGoodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      if(this.batchOpen == true){
        this.$refs.upload.clearFiles()
      }
      this.batchOpen = false;
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        displaySkuSoId: null,
        skuId: null,
        skuName: null,
        projectId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        removed: null
      };
      this.imageUrl = "";
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加平台陈列V5柜商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPlatformProjectDisplayGoods(id).then(response => {
        this.form = response.data;
        this.form.newGoods = response.data.newGoods.toString();
        this.form.goodsType = response.data.goodsType.toString();
        this.open = true;
        this.title = "修改平台陈列V5柜商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let params = {
            ...this.form,
            imageUrl:this.imageUrl|| this.form.imageUrl,
            newGoods : parseInt(this.form.newGoods),
            goodsType : parseInt(this.form.goodsType),
          }
          if (this.form.id != null) {
            updatePlatformProjectDisplayGoods(params).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPlatformProjectDisplayGoods(params).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除平台陈列V5柜商品编号为"' + ids + '"的数据项？').then(function() {
          // 修改为逻辑删除
        return removedPlatformProjectDisplayGoods(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('genius/platform-project-display-goods/export', {
        ...this.queryParams
      }, `platform-project-display-goods_${new Date().getTime()}.xlsx`)
    },
    //图片上传成功
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.imageUrl = res.data.url;
      } else {
        this.$message.error("图片上传失败");
        console.log("图片上传失败");
      }
    },
  }
};
</script>
<style scoped>
 
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  position: relative;
  overflow: hidden;

  display: flex;
  text-align: center;
  cursor: pointer;
  outline: none;
  justify-content: center;
  align-items: center;
  height: 100px;
  width: 100px;
}

::v-deep.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}


</style>